package com.example.zzh.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zzh.entity.ZzhFunction;
import com.example.zzh.entity.ZzhOrganization;
import com.example.zzh.entity.ZzhRole;
import com.example.zzh.entity.ZzhStaff;
import com.example.zzh.service.ZzhFunctionService;
import com.example.zzh.service.ZzhOrganizationService;
import com.example.zzh.service.ZzhRoleService;
import com.example.zzh.service.ZzhStaffService;
import com.example.zzh.utils.JwtTokenUtils;
import com.example.zzh.utils.Result;
import com.example.zzh.utils.ResultGenerator;
import com.example.zzh.utils.Sha256Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zzh
 * @since 2023-07-28
 */
@Api(tags = "用户控制器")
@RestController
@RequestMapping("/zzh-staff")
public class ZzhStaffController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ZzhStaffService zzhStaffService;

    @Autowired
    ZzhOrganizationService zzhOrganizationService;

    @Autowired
    private ZzhRoleService zzhRoleService;

    @GetMapping("/list")
    @ApiOperation(value = "查询所有员工(查询)", notes = "查询所有员工信息")
    public Result list(){
        return ResultGenerator.genSuccessResult(zzhStaffService.list());
    }

    @GetMapping("/option")
    @ApiOperation(value = "查询下拉角色和部门列表", notes = "查询下拉角色和部门列表")
    public Result option(){
        List<ZzhRole> zzhRoles=zzhRoleService.lambdaQuery().eq(ZzhRole::getStatus,1).list();
        Map<Long,String> hashMapRoles=new HashMap<Long, String>();
        for (ZzhRole i : zzhRoles) {
            if(i.getId()==1) continue;
            hashMapRoles.put(i.getId(),i.getName());
        }
        List<ZzhOrganization> zzhOrganizations=zzhOrganizationService.lambdaQuery().eq(ZzhOrganization::getDeleteFlag,"1").list();
        Map<Long,String> hashMapOrganizations=new HashMap<Long, String>();
        for (ZzhOrganization i : zzhOrganizations) {
            hashMapOrganizations.put(i.getId(),i.getOrgAbr());
        }
        Map<String,Object> data=new HashMap<>();
        data.put("hashMapRoles",hashMapRoles);
        data.put("hashMapOrganizations",hashMapOrganizations);
        return ResultGenerator.genSuccessResult(data);
    }

    @PostMapping("/list")
    @ApiOperation(value = "查询所有员工分页", notes = "分页")
    public Result list(@RequestBody Map<String,Object> params){
        if (StringUtils.isEmpty(params.get("page")) || StringUtils.isEmpty(params.get("limit"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        Page<ZzhStaff> page=new Page<>();
        page.setCurrent((int) params.get("page"));
        page.setSize((int) params.get("limit"));
        LambdaQueryWrapper<ZzhStaff> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        IPage r=null;
        if(!StringUtils.isEmpty(params.get("username"))){
            lambdaQueryWrapper.like(ZzhStaff::getUsername,params.get("username"));
        }
        if(!StringUtils.isEmpty(params.get("department"))){
            lambdaQueryWrapper.eq(ZzhStaff::getDepartment,params.get("department"));
        }
        lambdaQueryWrapper.in(ZzhStaff::getStatus,1,2);
        r=zzhStaffService.pageNames(page,lambdaQueryWrapper);
        return ResultGenerator.genSuccessResult(r.getRecords(),r.getTotal());
    }

    @PutMapping("/updateStatus")
    @ApiOperation(value = "修改员工状态", notes = "修改员工状态")
    public Result updateStatus(@RequestParam Long id){
        if(id==1){
            return ResultGenerator.genErrorResult(404,"不能更改超级管理员状态");
        }
        ZzhStaff zzhStaff=zzhStaffService.getRoleById(id);
        if(!Objects.isNull(zzhStaff)){
            if(zzhStaff.getStatus()==1){
                zzhStaff.setStatus(2);
            }else if(zzhStaff.getStatus()==2){
                zzhStaff.setStatus(1);
            }
            if(zzhStaffService.updateById(zzhStaff)) {
                return ResultGenerator.genSuccessResult();
            }
            return ResultGenerator.genErrorResult(404,"更新不成功");
        }else {
            return ResultGenerator.genErrorResult(404,"更新不成功");
        }
    }


    @PostMapping("/add")
    @ApiOperation(value = "新增员工", notes = "新增员工信息")
    public Result add(@RequestBody ZzhStaff zzhStaff){
        zzhStaff.setPassword(Sha256Util.hashString("123456"));
        if(zzhStaffService.save(zzhStaff)){
            return ResultGenerator.genSuccessResult();
        }else {
            return ResultGenerator.genErrorResult(404,"新增不成功");
        }
    }

    @PostMapping("/addOrMod")
    @ApiOperation(value = "新增或修改员工", notes = "新增或修改员工信息")
    public Result addOrMod(@RequestBody ZzhStaff zzhStaff){
        zzhStaff.setPassword(Sha256Util.hashString("123456"));
        if(zzhStaffService.saveOrUpdate(zzhStaff)){
            return ResultGenerator.genSuccessResult();
        }else {
            return ResultGenerator.genErrorResult(404,"新增不成功");
        }
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改员工", notes = "修改员工信息")
    public Result mod(@RequestBody ZzhStaff zzhStaff){
        if(zzhStaff.getId()==1){
            return ResultGenerator.genErrorResult(404,"不能更改超级管理员信息");
        }
        if(zzhStaffService.updateById(zzhStaff)){
            return ResultGenerator.genSuccessResult();
        }else {
            return ResultGenerator.genErrorResult(404,"修改不成功");
        }
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除员工", notes = "删除员工信息")
    public Result delete(@RequestParam Long id){
        ZzhStaff zzhStaff=zzhStaffService.getRoleById(id);
        if(!Objects.isNull(zzhStaff)){
            zzhStaff.setStatus(0);
            if(zzhStaffService.updateById(zzhStaff)) {
                return ResultGenerator.genSuccessResult();
            }
            return ResultGenerator.genErrorResult(404,"删除不成功");
        }else {
            return ResultGenerator.genErrorResult(404,"删除不成功");
        }
    }

    @PostMapping("/like")
    @ApiOperation(value = "模糊查询姓名", notes = "模糊查询姓名")
    public List<ZzhStaff> like(@RequestBody ZzhStaff zzhStaff){
        LambdaQueryWrapper<ZzhStaff> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.like(ZzhStaff::getUsername,zzhStaff.getUsername());
        return zzhStaffService.list(lambdaQueryWrapper);
    }

    @PostMapping("/findeByLoginName")
    @ApiOperation(value = "查询是否重复", notes = "查询是否重复")
    public Result findeByLoginName(@RequestParam String loginName){
        List list=zzhStaffService.lambdaQuery().eq(ZzhStaff::getLoginName,loginName).list();
        return list.size()>0?ResultGenerator.genSuccessResult(list):ResultGenerator.genFailResult("不重复");
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    public Result login(@RequestBody ZzhStaff zzhStaff){
        String password=Sha256Util.hashString(zzhStaff.getPassword());
        List list=zzhStaffService.lambdaQuery().eq(ZzhStaff::getLoginName,zzhStaff.getLoginName())
                .eq(ZzhStaff::getPassword,password).list();
        if(list.size()>0){
            ZzhStaff zzhStaff1= (ZzhStaff) list.get(0);
            // 获取Session对象
            HttpSession session = request.getSession();
            // 将用户信息存储到Session中
            session.setAttribute("user", zzhStaff1);
            JwtTokenUtils jwtTokenUtils=new JwtTokenUtils();
            String jwtToken=jwtTokenUtils.generateJwtToken(zzhStaff1);
            HashMap hashMap=new HashMap();
            hashMap.put("user",zzhStaff1);
            hashMap.put("jwt",jwtToken);
            return ResultGenerator.genSuccessResult(hashMap);
        }
        return ResultGenerator.genFailResult("");
    }

    @PostMapping("/updatePassWord")
    @ApiOperation(value = "更新密码", notes = "更新密码")
    public Result updatePassWord(@RequestBody Map<String,Object> params){
        System.out.println("-----------------");
        if (StringUtils.isEmpty(params.get("low")) || StringUtils.isEmpty(params.get("new"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        System.out.println(params.get("low").toString());
        System.out.println(params.get("new").toString());
        // 获取Session对象
        HttpSession session = request.getSession();
        // 将用户信息存储到Session中
        ZzhStaff zzhStaff=(ZzhStaff) session.getAttribute("user");
        if(zzhStaff.getPassword().equals(Sha256Util.hashString(params.get("low").toString()))){
            zzhStaff.setPassword(Sha256Util.hashString(params.get("new").toString()));
        }else {
            return ResultGenerator.genErrorResult(404,"旧密码错误");
        }
        if(zzhStaffService.saveOrUpdate(zzhStaff)){
            return ResultGenerator.genSuccessResult();
        }else {
            return ResultGenerator.genErrorResult(404,"更新密码不成功");
        }
    }

}